using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

[CanEditMultipleObjects]
[CustomEditor(typeof(RenderSortingOrderSetting))]
class RenderSortingOrderSettingEditor : Editor
{
	// Serialized properties are going to be far too much hassle
    private RenderSortingOrderSetting[] targetScript = new RenderSortingOrderSetting[0];
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
	private Renderer[] renderers = new Renderer[0];
#endif

    public override void OnInspectorGUI()
    {
		DrawSpriteEditorGUI();
    }
   
    protected T[] GetTargetsOfType<T>( Object[] objects ) where T : UnityEngine.Object {
    	List<T> ts = new List<T>();
    	foreach (Object o in objects) {
    		T s = o as T;
    		if (s != null)
    			ts.Add(s);
    	}
    	return ts.ToArray();
    }

    protected void OnEnable()
    {
        targetScript = GetTargetsOfType<RenderSortingOrderSetting>(targets);

#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
    	List<Renderer> rs = new List<Renderer>();
    	foreach (var v in targetScript) {
    		if (v != null && v.renderer != null) {
    			rs.Add(v.renderer);
    		}
    	}
    	renderers = rs.ToArray();
#endif
    }
	
    protected void DrawSpriteEditorGUI()
	{
        GUILayout.Space(8);
        
        if (targetScript.Length > 0)
        {
            bool isNeedChildContol = EditorGUILayout.Toggle("Order In Layer", targetScript[0].isNeedChildControl);
            if (isNeedChildContol != targetScript[0].isNeedChildControl)
            {
                Undo.RecordObjects(targetScript, "NeedChildControl");
                foreach (RenderSortingOrderSetting r in targetScript)
                {
                    r.isNeedChildControl = isNeedChildContol;                    
                }
            }

            string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", targetScript[0].LayerName);
            if (sortingLayerName != targetScript[0].LayerName)
            {
                Undo.RecordObjects(targetScript, "Sorting Layer");
                foreach (RenderSortingOrderSetting r in targetScript)
                {
                    r.LayerName = sortingLayerName;
	            }
	        }

			int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetScript[0].SortingOrder);
            if (sortingOrder != targetScript[0].SortingOrder)
            {
	            tk2dUndo.RecordObjects(targetScript, "Order In Layer");
	            tk2dUndo.RecordObjects(renderers, "Order In Layer");
                foreach (RenderSortingOrderSetting s in targetScript)
                {
                    s.SortingOrder = sortingOrder;
	            }
			}
		}
	}
}

